import pymysql

# 打开数据库连接
conn = pymysql.connect(host='localhost', user="root", passwd="root", db="siya")
conn.select_db('face_detect')
# 获取游标
cur = conn.cursor()


def check_username(username):
    sql = "select * from user where username=%s"
    cur.execute(sql, username)

    print('sql执行成功')
    # 没有该用户名
    if len(cur.fetchall()) == 0:
        print(len(cur.fetchall()))

        print("用户名没有重复")
        return 1
    # 有该用户名
    else:
        print("用户名重复")
        return 0


def check_pwd(username, password):
    sql = "select * from user where username=%s and password=%s"
    cur.execute(sql, (username, password))
    if cur.fetchone() is not None:
        return 1
    else:
        return 0


def insert_username_pwd(username, password):
    sql = "INSERT INTO user (username,password) VALUES  (%s,%s); "
    insert = cur.execute(sql, (username, password))
    print(insert)
    conn.commit()
    if insert == 1:
        return 1
    else:
        return 0


def close_db():
    cur.close()
    conn.close()


def insert_user(username):
    f = open("register_img/test.png", "rb")
    img = f.read()
    sql = "INSERT INTO user (username,img) VALUES  (%s,%s); "
    insert = cur.execute(sql, (username, img))
    print(insert)
    conn.commit()


def get_user_face(username):
    sql = "select img from user where username = %s;"
    cur.execute(sql, username)
    # print(cur.fetchone()[0])
    try:
        fout = open('login_img/quchu1.png', 'wb')
        fout.write(cur.fetchone()[0])
    except Exception:
        return 0

    return 1
